package com.yk.client;

import com.yk.clienthandler.MessageSendHandler;
import com.yk.decode.RpcDecoder;
import com.yk.decode.RpcEncoder;
import com.yk.pojo.ReqMessage;
import com.yk.pojo.RespMessage;
import com.yk.pool.CommonInterface;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by dingkl on 2017/7/28.
 */
public class RPCClient implements CommonInterface{

    private EventLoopGroup eventLoopGroup;

    private String host;

    private int port;

    private Loader loader;


    public RPCClient(EventLoopGroup eventLoopGroup,String host,int port,Loader loader){
        this.eventLoopGroup = eventLoopGroup;
        this.host = host;
        this.port = port;
        this.loader = loader;
    }

    @Override
    public void execute() throws Exception {
        connect();
    }

    @Override
    public void handlerExecute(Runnable r, ThreadPoolExecutor executor) throws Exception {

    }

    public void connect(){
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE,true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                //java序列化
                //socketChannel.pipeline().addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingResolver(this.getClass().getClassLoader())));
                //socketChannel.pipeline().addLast(new ObjectEncoder());

                socketChannel.pipeline().addLast(new RpcEncoder(ReqMessage.class));
                socketChannel.pipeline().addLast(new RpcDecoder(RespMessage.class));

                socketChannel.pipeline().addLast(new MessageSendHandler());

            }
        });
        ChannelFuture future = bootstrap.connect(host,port);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()){
                    System.out.println("连接服务成功");
                    MessageSendHandler handler = channelFuture.channel().pipeline().get(MessageSendHandler.class);
                RPCClient.this.loader.setMessageSendHandler(handler);
                }
            }
        });
    }
}
